package com.atguigu.mock.util;

import com.google.common.base.CaseFormat;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapUtil {


    public static <K,T> Map<K,T> getMapFromList(List<T> list, String keyName ){

        Map<K,T> map= new HashMap();
        K key ;
        try {
            for (T entity : list) {
                String keyNameUp = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, keyName);
                Method method = entity.getClass().getDeclaredMethod("get"+keyNameUp);
                key = (K)method.invoke(entity);
                map.put(key,entity);
            }
            return  map ;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("can't get id from the entity");
        }
    }


    public static <T> Map<Long,T> getIdMapFromList(List<T> list, String keyName ){

        Map<Long,T> map= new HashMap();
        Long key ;
        try {
            for (T entity : list) {
                String keyNameUp = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, keyName);
                Method method = entity.getClass().getDeclaredMethod("get"+keyNameUp);
                key = (Long)method.invoke(entity);
                map.put(key,entity);
            }
            return  map ;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("can't get id from the entity");
        }
    }
}
